const Koa = require('koa');

let app = new Koa;
const router = require('koa-simple-router');
const fs = require('fs');
const path = require('path');
const { resolve } = require('path');

app.listen(8080,(req,res) => {
    console.log('====>','koa running...');
})
//整合请求和响应为ctx
app.use((ctx,next) => {
    ctx.body = {
        name: 'hello',
        age:18
    }
})

app.use(router(_ => {
    _.get('/',(ctx,next) => {
        ctx.type = 'html';
        ctx.body = fs.readFileSync(path.join(__dirname,'static/request.html'))
    })

    _.get('/',async (ctx,next) => {
        if(count >= 3){
            ctx.status = 500
            ctx.body = '请求次数过多,请求稍后重试！！！';
            return
        }

        await next()
        if(ctx.bool){
            count++;
        }
    })
    _.get('/index',async (ctx,next) => {
        let random = Math.random() * 10

        await new Promise((resolvs,reject) => {
            setTimeout(() => {
                if(random > 5){
                    ctx.body = `'request'${random}大于5`;
                    ctx.bool = true;
                    reselve()
                }else{
                    ctx.body = `'request'${random} < 5`;
                    resolve()
                }
            },100)
        })
    })


    
}))